package com.example.himalaya.view.fragments;

import android.content.Intent;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.himalaya.R;
import com.example.himalaya.view.activity.DetailActivity;
import com.example.himalaya.view.adapters.AlbumListAdapter;
import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.base.BaseFragment;
import com.example.himalaya.view.callback.ISubscriptionViewCallback;
import com.example.himalaya.constants.Constants;
import com.example.himalaya.presenters.AlbumDetailPresenter;
import com.example.himalaya.presenters.SubscriptionPresenter;
import com.example.himalaya.utils.LogUtil;
import com.example.himalaya.view_component.ConfirmDialog;
import com.example.himalaya.view_component.UILoader;
import com.ximalaya.ting.android.opensdk.model.album.Album;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.List;
import java.util.Objects;

public class SubscriptionViewFragment extends BaseFragment implements ISubscriptionViewCallback {

    // Constance
    private static final String TAG = "SubscriptionViewFragment";

    // UI object

    private RecyclerView mSubListView;

    // logic object
    private Album mCurrentClickAlbum = null;

    private SubscriptionPresenter mSubscriptionPresenter;

    // Adapter
    private AlbumListAdapter mAlbumListAdapter = null;
    private UILoader mUiLoader = null;
    private View mSuccessView;

    @Override
    protected View onSubViewLoaded(final LayoutInflater layoutInflater, ViewGroup container) {


        if (mUiLoader == null) {
            mUiLoader = new UILoader(container.getContext()) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSuccessView(layoutInflater, container);
                }


                @Override
                protected View getEmptyView() {

                    View itemView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_empty_view, this, false);

                    TextView tipsView = itemView.findViewById(R.id.tips_for_empty);

                    tipsView.setText(R.string.tips_for_empty_sub);
                    return itemView;
                }
            };

            if (mUiLoader.getParent() instanceof ViewGroup) {
                ((ViewGroup) mUiLoader.getParent()).removeView(mUiLoader);
            }

        }


        return mUiLoader;
    }


    private View createSuccessView(LayoutInflater layoutInflater, ViewGroup container) {


        mSuccessView = layoutInflater.inflate(R.layout.fragment_subscription, container, false);

        initSuccessVariable();

        initSuccessAdapter();

        initSuccessPresenter();

        initSuccessListener();

        initSuccessData();
        initSuccessView();

        return mSuccessView;
    }

    private void initSuccessListener() {
        // 设置需要响应的UI事件
        mAlbumListAdapter.setAlbumItemClickListener(new AlbumListAdapter.onAlbumItemClickListener() {
            @Override
            public void onItemClick(int position, Album album) {
                AlbumDetailPresenter.getInstance().setTargetAlbum(album);

                // item被点击了, 跳到当前item的详情界面
                // 根据位置拿到数据

                Intent intent = new Intent(getContext(), DetailActivity.class);

                startActivity(intent);
            }
        });

        mAlbumListAdapter.setAlbumItemLongClickListener(new AlbumListAdapter.onAlbumItemLongClickListener() {
            /**
             * 界面 item 长按的功能
             * 删除订阅
             *
             * @param album 用户点击选择的专辑对象
             */
            @Override
            public void onItemLongClick(Album album) {

                mCurrentClickAlbum = album;

                // 删除订阅
                // Toast.makeText(BaseApplication.getAppContext(), "长按删除订阅", Toast.LENGTH_LONG).show();

                ConfirmDialog confirmDialog = new ConfirmDialog(Objects.requireNonNull(getActivity()));

                // 设置需要处理的监听事件
                confirmDialog.setonDialogActionClickListener(new ConfirmDialog.onDialogActionClickListener() {
                    @Override
                    public void onRightBtnClick() {
                        // 不做事件
                    }

                    @Override
                    public void onLeftBtnClick() {
                        // 删除订阅的专辑
                        if (mCurrentClickAlbum != null) {
                            mSubscriptionPresenter.deleteSubscription(mCurrentClickAlbum);
                        }
                    }
                });

                confirmDialog.show();
            }
        });
    }

    private void initSuccessVariable() {
        // 显示内容部分
        mSubListView = mSuccessView.findViewById(R.id.sub_list);
    }

    private void initSuccessAdapter() {
        if (mAlbumListAdapter == null) {
            mAlbumListAdapter = new AlbumListAdapter();
        }

    }

    private void initSuccessPresenter() {
        mSubscriptionPresenter = SubscriptionPresenter.getInstance();

        mSubscriptionPresenter.registerViewCallback(this);
    }

    private void initSuccessView() {
        mSubListView.setLayoutManager(new LinearLayoutManager(mSuccessView.getContext()));
        mSubListView.setAdapter(mAlbumListAdapter);

        mSubListView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UIUtil.dip2px(view.getContext(), 5);
                outRect.bottom = UIUtil.dip2px(view.getContext(), 5);
                outRect.left = UIUtil.dip2px(view.getContext(), 5);
                outRect.right = UIUtil.dip2px(view.getContext(), 5);
            }
        });


        // 初始化界面状态（加载中）
        if (mUiLoader != null) {
            mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
        }
    }

    private void initSuccessData() {
        // 一开始从数据库拿到已有数据
        mSubscriptionPresenter.getSubscriptionList();
    }

    @Override
    public void onAddResult(boolean isSuccess) {

        LogUtil.d(TAG, "回来没老弟");
        mSubscriptionPresenter.getSubscriptionList();
    }


    /**
     * 删除订阅的回调
     *
     * @param isSuccess 是否成功
     */
    @Override
    public void onDeleteResult(boolean isSuccess) {
        // 一开始从数据库拿到已有数据
        initSuccessData();

        Toast.makeText(BaseApplication.getAppContext(), "删除订阅" + (isSuccess ? "成功" : "失败"), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onSubscriptsLoaded(List<Album> albums) {
        // 根据数据库的数据 更新UI


        if (albums != null && mUiLoader != null) {
            LogUtil.d(TAG, "albums size -->" + albums.size());

            if (albums.size() == 0) {
                // 改变界面状态（数据为空）
                mUiLoader.updateStatus(UILoader.UIStatus.EMPTY);
                return;
            }

            mUiLoader.updateStatus(UILoader.UIStatus.SUCCESS);

            mAlbumListAdapter.setData(albums);
        } else {
            // 改变界面状态（数据为空）
            if (mUiLoader != null) {
                mUiLoader.updateStatus(UILoader.UIStatus.ERROR);
            }
            Toast.makeText(BaseApplication.getAppContext(), "未知的错误", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onSubFull() {
        Toast.makeText(BaseApplication.getAppContext(), "订阅失败，订阅太多了 > " + Constants.MAX_SUB_COUNT, Toast.LENGTH_LONG).show();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSubscriptionPresenter != null) {
            mSubscriptionPresenter.unRegisterViewCallback(this);
        }

        if (mAlbumListAdapter != null) {
            mAlbumListAdapter.setAlbumItemClickListener(null);
        }
    }


}
